﻿/*
 * Simple XPath Compatibility Plugin for Ctn 1.1
 * By John Resig
 * Dual licensed under MIT and GPL.
 */

(function(Ctn){

var find = Ctn.find;
//重写find函数
Ctn.find = function(selector, context){

	// 将根目录 / 转化上下文为
	if (!selector.indexOf("/")) {
		context = context.ownerDocument || context;
	}
	
	//如果使用/搜索，且第一个不是/，则在最前加>表示从当前儿子中搜索
	if (selector.indexOf("/") > 0) {
	    selector = ">" + selector;
	}

	// 将 // 转换为 " " (在子孙中查找)
	selector = selector.replace(/\/\//g, " ");

	// 将 / 转换为 > (在儿子中查找)
	selector = selector.replace(/\//g, ">");

	// 将 [elem] 转换为 :has(elem) (判断是否存在)
	selector = selector.replace(/\[([^@].*?)\]/g, function(m, selector){
		return ":has(" + selector + ")";
	});

	// 将 /.. 转换为 新的表达式 (查找父亲)
	if ( selector.indexOf(">..") >= 0 ) {
		var parts = selector.split(/>\.\.>?/g);
		var cur = Ctn(parts[0], context);

		for ( var i = 1; i < parts.length; i++ )
			cur = cur.parent(parts[i]);

		return cur.get();
	}

	return find(selector, context);
};
Ctn.prototype.extend({
//扩展selectNodes
selectNodes: function(exp){
    return this.find(exp);
},
//扩展selectSingleNode
selectSingleNode: function(exp){
    return this.find(exp.trim() + ':first');
}
});

//获取xml文档
Ctn.getXmlDoc = function(){
    return Ctn.tryeach(
        function() {return document.implementation.createDocument('','',null)},
        function() {return new ActiveXObject("Msxml2.DOMDocument.4.0")},
        function() {return new ActiveXObject("Microsoft.XMLDOM")}
    );
};
//对非IE浏览器添加loadXML方法
if (!!window.XMLDocument && !XMLDocument.prototype.loadXML){
    XMLDocument.prototype.loadXML = function(xmlString){
        var childNodes = this.childNodes;
        for (var i = childNodes.length - 1; i >= 0; i--)
            this.removeChild(childNodes[i]);
        var dp = new DOMParser();
        var newDOM = dp.parseFromString(xmlString, "text/xml");
        var newElt = this.importNode(newDOM.documentElement, true);
        this.appendChild(newElt);
    }
}
})(Ctn);

